package com.sky.service.impl;

import com.sky.dto.DataOverViewQueryDTO;
import com.sky.entity.Orders;
import com.sky.mapper.ReportMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import io.swagger.models.auth.In;
import org.apache.poi.util.Internal;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private ReportMapper reportMapper;
    @Autowired
    private WorkspaceService workspaceService;

    //营业额统计
    @Transactional
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {

        List<LocalDate> localDateList = new ArrayList<>();
        List<Double> doubleList = new ArrayList<>();

        localDateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            localDateList.add(begin);

        }

        //查询每天的营业额
        for (LocalDate date : localDateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover = reportMapper.sumBytTurnoverMap(map);
            turnover = turnover == null ? 0.0 : turnover;
            doubleList.add(turnover);
        }

        String dateListStr = StringUtils.collectionToCommaDelimitedString(localDateList);
        String turnoverListStr = StringUtils.collectionToCommaDelimitedString(doubleList);

        return TurnoverReportVO
                .builder()
                .dateList(dateListStr)
                .turnoverList(turnoverListStr)
                .build();
    }

    //用户统计
    @Transactional
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> localDateList = new ArrayList<>();
        List<Integer> newUserList = new ArrayList<>();
        List<Integer> totalUserList = new ArrayList<>();
        localDateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            localDateList.add(begin);
        }
        Integer total = 0;
        //select * from user where create_time > begin and create_time < end
        for (LocalDate date : localDateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("begin", beginTime);
            map.put("end", endTime);
            Integer newUser =  reportMapper.sumByUserMap(map);
            newUser = newUser == null ? 0 : newUser;
            newUserList.add(newUser);
            total += newUser;
        }
        for (int i = 0; i < localDateList.size(); i++) {
            totalUserList.add(total);
        }
        String dateListStr = StringUtils.collectionToCommaDelimitedString(localDateList);
        String newUserListStr = StringUtils.collectionToCommaDelimitedString(newUserList);
        String totalUserListStr = StringUtils.collectionToCommaDelimitedString(totalUserList);
        return UserReportVO.builder()
                .dateList(dateListStr)
                .newUserList(newUserListStr)
                .totalUserList(totalUserListStr)
                .build();
    }

    //订单统计
    @Transactional
    @Override
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {

        List<LocalDate> localDateList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();
        List<Integer> orderCountList = new ArrayList<>();
        localDateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            localDateList.add(begin);
        }
        Integer validOrderCount = 0;
        Integer totalOrderCount = 0;
        for (LocalDate date : localDateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", Orders.COMPLETED);
            Integer ordersDou = reportMapper.sumOrdersByMap(map);
            ordersDou = ordersDou == null ? 0 : ordersDou;
            validOrderCountList.add(ordersDou);
            validOrderCount += ordersDou;
            map.remove("status");
            Integer ordersAll = reportMapper.sumOrdersByMap(map);
            ordersAll = ordersAll == null ? 0 : ordersAll;
            orderCountList.add(ordersAll);
            totalOrderCount+=ordersAll;
        }
        String dateListStr = StringUtils.collectionToCommaDelimitedString(localDateList);
        String validOrderCountListStr = StringUtils.collectionToCommaDelimitedString(validOrderCountList);
        String orderCountListStr = StringUtils.collectionToCommaDelimitedString(orderCountList);
        Double orderCompletionRate =  validOrderCount/(totalOrderCount/1.0);
        return OrderReportVO.builder()
                .dateList(dateListStr) //日期，以逗号分隔
                .validOrderCountList(validOrderCountListStr)//每日有效订单数，以逗号分隔
                .orderCountList(orderCountListStr)//每日订单数，以逗号分隔
                .totalOrderCount(totalOrderCount) //订单总数
                .validOrderCount(validOrderCount)//有效订单数
                .orderCompletionRate(orderCompletionRate) //订单完成率
                .build();
    }
    @Transactional
    @Override
    public SalesTop10ReportVO getTopTen(LocalDate begin, LocalDate end) {
        List<String> nameList = new ArrayList<>();
        List<String> numberList = new ArrayList<>();
        List<SalesTop10ReportVO> topTenList = reportMapper.getTopTen();

        for (SalesTop10ReportVO salesTop10ReportVO : topTenList) {
            nameList.add(salesTop10ReportVO.getNameList());
            numberList.add(salesTop10ReportVO.getNumberList());
        }

        String nameListStr = StringUtils.collectionToCommaDelimitedString(nameList);
        String numberListStr = StringUtils.collectionToCommaDelimitedString(numberList);

        return SalesTop10ReportVO.builder()
                .nameList(nameListStr)
                .numberList(numberListStr)
                .build();
    }

    @Override
    public void exportBusinessData(HttpServletResponse response) {
        //查询数据
        LocalDate date = LocalDate.now();
        LocalDate begin = date.plusDays(-31);
        LocalDate end = date.plusDays(-1);

        List<BusinessDataVO> list = new ArrayList<>();
        BusinessDataVO businessDataVO = null;
        while (!begin.equals(end)) {
            businessDataVO = workspaceService.getBusinessData(begin);
            begin = begin.plusDays(1);
            list.add(businessDataVO);
            System.out.println("businessDataVO===="+businessDataVO);
        }
        Double turnover = 0.0;//营业额
        Integer validOrderCount = 0;//有效订单数
        Double orderCompletionRate = 0.0;//订单完成率
        Double unitPrice = 0.0;//平均客单价
        Integer newUsers = 0;//新增用户数
        for (BusinessDataVO bv : list) {
            turnover += bv.getTurnover();
            validOrderCount += bv.getValidOrderCount();
            orderCompletionRate += bv.getOrderCompletionRate();
            unitPrice += bv.getUnitPrice();
            newUsers += bv.getNewUsers();
            System.out.println(bv);
        }
        System.out.println(list);
        //将数据写入到Excel文件中
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            XSSFWorkbook excel = new XSSFWorkbook(inputStream);
            XSSFSheet sheet = excel.getSheet("Sheet1");
            begin = date.plusDays(-30);
            end = date.plusDays(-1);
            sheet.createRow(1).createCell(1).setCellValue(begin+"-"+end);
            XSSFRow row = sheet.createRow(3);
            row.createCell(2).setCellValue(turnover);
            row.createCell(4).setCellValue(validOrderCount);
            row.createCell(6).setCellValue(orderCompletionRate);
            row = sheet.createRow(4);
            row.createCell(2).setCellValue(unitPrice);
            row.createCell(4).setCellValue(newUsers);

            for (int i = 0; i <30; i++) {
                row = sheet.createRow(7 + i);
                row.createCell(1).setCellValue(begin.toString());
                begin = begin.plusDays(1);
                row.createCell(2).setCellValue(list.get(i).getTurnover());
                row.createCell(3).setCellValue(list.get(i).getValidOrderCount());
                row.createCell(4).setCellValue(list.get(i).getOrderCompletionRate());
                row.createCell(5).setCellValue(list.get(i).getUnitPrice());
                row.createCell(6).setCellValue(list.get(i).getNewUsers());
            }

            //通过输出流将Excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
